package com.incar.chuxing.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.incar.chuxing.R;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlConstant;
import com.incar.chuxing.baiduMap.GeoCoderUtils;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.ExistingTravel;
import com.incar.chuxing.bean.ParkDetailBean;
import com.incar.chuxing.bean.PlaceOrderBean;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.utils.AccountStatus;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.InCarDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.IntentUtils;
import com.incar.chuxing.utils.MyApplication;
import com.incar.chuxing.utils.SharedPreferencesKey;
import com.incar.chuxing.utils.SharedPreferencesUtils;
import com.incar.chuxing.utils.Toast.ToastCompat;
import com.zhy.autolayout.AutoLinearLayout;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChooseInsuranceActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_more)
    ImageView titleMore;
    @BindView(R.id.iv_confirm_rent_car)
    ImageView ivConfirmRentCar;
    @BindView(R.id.tv_confirm_brand)
    TextView tvConfirmRentBrand;
    @BindView(R.id.tv_confirm_license)
    TextView tvConfirmLicense;
    @BindView(R.id.tv_confirm_rent_seats)
    TextView tvConfirmRentSeats;
    @BindView(R.id.tv_confirm_rent_battery)
    TextView tvConfirmRentBattery;
    @BindView(R.id.tv_time_fee)
    TextView tvTimeFee;
    @BindView(R.id.tv_duration_fee)
    TextView tvDurationFee;
    @BindView(R.id.tv_min_fee)
    TextView tvMinFee;
    @BindView(R.id.tv_confirm_rent_parkName)
    TextView tvConfirmRentParkName;
    @BindView(R.id.progressBar_rent)
    AutoLinearLayout progressBar_rent;
    @BindView(R.id.tv_confirm_rent_sdew)
    TextView tvConfirmRentSdew;
    @BindView(R.id.rb_confirm_rent_sdew)
    RadioButton rbAbatement;
    private Context mContext = this;
    private LatLng carLatLngPoint;
    private ParkDetailBean.AttachmentBean.CarsBean carsBean;
    private String carId;
    private String parkId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_insurance;
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        carsBean = (ParkDetailBean.AttachmentBean.CarsBean) bundle.getSerializable("carsBean");
        carLatLngPoint = new LatLng(carsBean.getLatitude(), carsBean.getLongitude());
        GeoCoderUtils.getInstance().reverseGeoCode(carLatLngPoint, new GeoCoderUtils.OnGeoListener() {
            @Override
            public void onGeoSuccess(String address) {
                tvConfirmRentParkName.setText(address);
            }

            @Override
            public void onGeoFailure() {
                tvConfirmRentParkName.setText("未能获取位置信息");
            }
        });
        tvConfirmRentBrand.setText(carsBean.getBrand() + " " + carsBean.getModel());
        tvConfirmLicense.setText(carsBean.getLicenseTag());
        tvConfirmRentSeats.setText(carsBean.getSeat() + "座");
        tvConfirmRentBattery.setText(carsBean.getMileage() + "公里");
        tvTimeFee.setText(((carsBean.getValuationRuleModel().getWeekDayPrice()) / 100.0) + "");
        tvDurationFee.setText(((carsBean.getValuationRuleModel().getMileagePrice()) / 100.0) + "");
        tvMinFee.setText(((carsBean.getValuationRuleModel().getStartingPrice()) / 100.0) + "");
        //保险价格
        tvConfirmRentSdew.setText("不计免赔：" + carsBean.getAbatement() + "元/单");
        Glide.with(mContext).load(((MyApplication) getApplication()).getImageUrl() + carsBean.getPicture()).into(ivConfirmRentCar);
    }

    @Override
    public void initView() {
        titleName.setText("选择保险");
    }


    @OnClick({R.id.title_back, R.id.linearLayout_confirm_rent_rules, R.id.tv_confirm_rent_confirm, R.id.linearLayout_confirm_rent_insurance})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.linearLayout_confirm_rent_rules:
                Intent intent = new Intent();
                intent.setClass(mContext, WebViewActivity.class);
                intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "计价规则");
                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.VALUE_RULES);
                startActivity(intent);
                break;
            case R.id.tv_confirm_rent_confirm:
                if (!AccountStatus.isLogin(mContext)) {
                    ToastCompat.makeText(mContext, getResources().getString(R.string.loginFirst), Toast.LENGTH_SHORT).show();
                    Intent intent1 = new Intent();
                    intent1.setClass(mContext, LoginActivity.class);
                    startActivity(intent1);
                } else {
                    carId = carsBean.getId() + "";
                    parkId = carsBean.getParkId() + "";
                    hasUnPayOrder();
                }
                break;

            case R.id.linearLayout_confirm_rent_insurance:
                Intent intent2 = new Intent();
                intent2.setClass(mContext, WebViewActivity.class);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlConstant.Request.INSURANCE);
                intent2.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "保险");
                startActivity(intent2);
                break;
        }
    }

    //下单
    public void rentCar(String carId, final String parkId, String isAbatement) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).rentCar(((MyApplication) getApplication()).getRequestFieldMap(), carId, parkId, isAbatement).enqueue(new Callback<PlaceOrderBean>() {
            @Override
            public void onResponse(Call<PlaceOrderBean> call, Response<PlaceOrderBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_rent.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        PlaceOrderBean.AttachmentBean.OrderBean result = response.body().getAttachment().getOrder();
                        String carBrand = "";
                        if (result.getCarModel().getModel() != null) {
                            carBrand = result.getCarModel().getBrand() + result.getCarModel().getModel();
                        }
                        String carPlate = result.getCarModel().getLicenseTag();
                        String carId = result.getCarId() + "";
                        String orderId = result.getId();
                        Intent intent = new Intent();
                        intent.putExtra("carBrand", carBrand);
                        intent.putExtra("carPlate", carPlate);
                        intent.putExtra(IntentKey.INTENT_ORDER_ID, orderId);
                        intent.putExtra("carId", carId);
                        intent.putExtra("picture", carsBean.getPicture());
                        intent.putExtra("parkId", parkId);
                        intent.putExtra("carLatitude", result.getCarModel().getLatitude() + "");
                        intent.putExtra("carLongitude", result.getCarModel().getLongitude() + "");
                        intent.putExtra("overplusTime", result.getOverplusTime());
                        intent.putExtra("userRemark", result.getCarModel().getUserRemark());
                        setResult(Constants.RESULT_RENT, intent);
                        finish();
                    } else if (response.body().getStatus() == 400) {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    } else if (response.body().getStatus() == 401) {
                        //这里只返回了一种不满足的资格，跳转资格认证步骤还需要获得其他资格状态，所以还需要checkUserStatus();
                        checkUserStatus(3);//未保证金
                    } else if (response.body().getStatus() == 402) {
                        checkUserStatus(1);//未实名
                    } else if (response.body().getStatus() == 403) {
                        checkUserStatus(2);//未认证
                    } else if (response.body().getStatus() == 404) {
                        progressBar_rent.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, "您有未完成订单", Toast.LENGTH_LONG).show();
                        final InCarDialog inCarDialog = new InCarDialog(mContext);
                        inCarDialog.setTitle(getString(R.string.dialogTitle));
                        inCarDialog.setMessage(getString(R.string.unPayOrder));
                        inCarDialog.setYesOnclickListener("支付", new InCarDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent(mContext, TravelRecordActivity.class);
                                startActivity(intent);
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.show();
                    } else if (response.body().getStatus() == 405) {
                        final InCarDialog inCarDialog = new InCarDialog(mContext);
                        inCarDialog.setTitle(getString(R.string.dialogTitle));
                        inCarDialog.setMessage(getString(R.string.rechargeRemind));
                        inCarDialog.setYesOnclickListener("充值", new InCarDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                Intent intent = new Intent(mContext, RechargeActivity.class);
                                startActivity(intent);
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                inCarDialog.dismiss();
                            }
                        });
                        inCarDialog.show();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar_rent.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<PlaceOrderBean> call, Throwable t) {
                progressBar_rent.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //跳转资格认证步骤需要获得其他资格状态，所以还需要checkUserStatus();
    private void checkUserStatus(final int SubmitFlag) {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar_rent.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEPOSIT_CAR_STATUS, response.body().getAttachment().getDepositStatus() + "");
                        if (SubmitFlag == 3) {
                            ToastCompat.makeText(mContext, "您还未支付保证金", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, QualificationActivity.class);
                            intent.putExtra("SubmitFlag", 3);
                            startActivity(intent);
                        } else if (SubmitFlag == 1) {
                            ToastCompat.makeText(mContext, "您还未实名认证和证照认证", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, QualificationActivity.class);
                            intent.putExtra("SubmitFlag", 1);
                            startActivity(intent);
                        } else if (SubmitFlag == 2) {
                            ToastCompat.makeText(mContext, "您还未证照认证", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(mContext, QualificationActivity.class);
                            intent.putExtra("SubmitFlag", 2);
                            startActivity(intent);
                        }
                    } else {
                        progressBar_rent.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                progressBar_rent.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("neterror", "008");
            }
        });
    }

    private void hasUnPayOrder() {
        progressBar_rent.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getExistingTravel(((MyApplication) getApplication()).getRequestFieldMap())
                .enqueue(new Callback<ExistingTravel>() {
                    @Override
                    public void onResponse(Call<ExistingTravel> call, final Response<ExistingTravel> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                if (response.body().getAttachment().getIsUnfinished() != 0) {
                                    progressBar_rent.setVisibility(View.GONE);
                                    switch (response.body().getAttachment().getStatus()) {
                                        case 15:
                                        case 16:
                                        case 17: {
                                            final InCarDialog inCarDialog = new InCarDialog(mContext);
                                            inCarDialog.setTitle(getString(R.string.dialogTitle));
                                            inCarDialog.setMessage(getString(R.string.unPayOrder));
                                            inCarDialog.setYesOnclickListener("支付", new InCarDialog.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    if (response.body().getAttachment().getOrderModel().getUserParkCompensate().equals("-1")) {
                                                        IntentUtils.toCarParkingFeeActivity(mContext, response.body().getAttachment().getOrderModel().getId());
                                                    } else {
                                                        IntentUtils.toPaymentActivity(mContext, response.body().getAttachment().getOrderModel().getId(), "");
                                                    }
                                                    inCarDialog.dismiss();
                                                }
                                            });
                                            inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    inCarDialog.dismiss();
                                                }
                                            });
                                            inCarDialog.setCancelable(false);
                                            inCarDialog.show();
                                        }
                                        break;
                                        case 10: {
                                            final InCarDialog inCarDialog = new InCarDialog(ChooseInsuranceActivity.this);
                                            inCarDialog.setTitle(getString(R.string.dialogTitle));
                                            inCarDialog.setMessage(getString(R.string.hasInDrivingOrder));
                                            inCarDialog.setYesOnclickListener("进入", new InCarDialog.onYesOnclickListener() {
                                                @Override
                                                public void onYesClick() {
                                                    Intent intentInUse = new Intent(mContext, DrivingActivity.class);
                                                    intentInUse.putExtra(IntentKey.INTENT_ORDER_ID, response.body().getAttachment().getOrderId());
                                                    startActivity(intentInUse);
                                                    inCarDialog.dismiss();
                                                    finish();
                                                }
                                            });
                                            inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                                                @Override
                                                public void onNoClick() {
                                                    inCarDialog.dismiss();
                                                }
                                            });
                                            inCarDialog.setCancelable(false);
                                            inCarDialog.show();
                                        }
                                        break;
                                    }
                                } else {  //没有未完成订单
                                    rentCar(carId, parkId, rbAbatement.isChecked() ? "1" : "2");
                                }
                            } else {
                                progressBar_rent.setVisibility(View.GONE);
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ExistingTravel> call, Throwable t) {
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_LONG).show();
                    }
                });
    }


}
